<template>
  <div class="picture-review-container">
    <a-card title="图片审核管理" :bordered="false">
      <!-- 搜索区域 -->
      <div class="search-form">
        <a-form :model="searchForm" layout="inline" @finish="handleSearch">
          <a-form-item label="图片名称" name="name">
            <a-input
              v-model:value="searchForm.name"
              placeholder="请输入图片名称"
              style="width: 200px"
              allow-clear
            />
          </a-form-item>
          <a-form-item label="审核状态" name="reviewStatus">
            <a-select
              v-model:value="searchForm.reviewStatus"
              placeholder="请选择审核状态"
              style="width: 120px"
              allow-clear
            >
              <a-select-option :value="0">待审核</a-select-option>
              <a-select-option :value="1">已通过</a-select-option>
              <a-select-option :value="2">已拒绝</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="分类" name="category">
            <a-input
              v-model:value="searchForm.category"
              placeholder="请输入分类"
              style="width: 120px"
              allow-clear
            />
          </a-form-item>
          <a-form-item>
            <a-space>
              <a-button type="primary" html-type="submit" :loading="loading">
                <template #icon><SearchOutlined /></template>
                搜索
              </a-button>
              <a-button @click="handleReset">
                <template #icon><ReloadOutlined /></template>
                重置
              </a-button>
            </a-space>
          </a-form-item>
        </a-form>
      </div>

      <!-- 统计信息 -->
      <div class="stats-cards">
        <a-row :gutter="16">
          <a-col :span="6">
            <a-card size="small" class="stat-card">
              <a-statistic
                title="待审核"
                :value="stats.pending"
                :value-style="{ color: '#faad14' }"
              >
                <template #prefix><ClockCircleOutlined /></template>
              </a-statistic>
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card size="small" class="stat-card">
              <a-statistic
                title="已通过"
                :value="stats.approved"
                :value-style="{ color: '#52c41a' }"
              >
                <template #prefix><CheckCircleOutlined /></template>
              </a-statistic>
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card size="small" class="stat-card">
              <a-statistic
                title="已拒绝"
                :value="stats.rejected"
                :value-style="{ color: '#ff4d4f' }"
              >
                <template #prefix><CloseCircleOutlined /></template>
              </a-statistic>
            </a-card>
          </a-col>
          <a-col :span="6">
            <a-card size="small" class="stat-card">
              <a-statistic title="总计" :value="stats.total" :value-style="{ color: '#1890ff' }">
                <template #prefix><PictureOutlined /></template>
              </a-statistic>
            </a-card>
          </a-col>
        </a-row>
      </div>

      <!-- 图片列表 -->
      <div class="picture-list">
        <a-spin :spinning="loading">
          <a-row :gutter="[16, 16]" v-if="pictureList.length > 0">
            <a-col
              :xs="24"
              :sm="12"
              :md="8"
              :lg="6"
              :xl="4"
              v-for="picture in pictureList"
              :key="picture.id"
            >
              <a-card
                :class="['picture-card', getReviewStatusClass(picture.reviewStatus)]"
                :cover="getPictureCover(picture)"
                size="small"
              >
                <template #actions>
                  <a-tooltip title="查看详情">
                    <EyeOutlined @click="handleViewDetail(picture)" />
                  </a-tooltip>
                  <a-tooltip title="通过审核" v-if="picture.reviewStatus === 0">
                    <CheckOutlined @click="handleReview(picture, 1)" />
                  </a-tooltip>
                  <a-tooltip title="拒绝审核" v-if="picture.reviewStatus === 0">
                    <CloseOutlined @click="handleReview(picture, 2)" />
                  </a-tooltip>
                  <a-tooltip title="编辑">
                    <EditOutlined @click="handleEdit(picture)" />
                  </a-tooltip>
                </template>
                <a-card-meta>
                  <template #title>
                    <a-tooltip :title="picture.name">
                      <span class="picture-title">{{ picture.name }}</span>
                    </a-tooltip>
                  </template>
                  <template #description>
                    <div class="picture-info">
                      <div class="status-tag">
                        <a-tag :color="getStatusColor(picture.reviewStatus)">
                          {{ getStatusText(picture.reviewStatus) }}
                        </a-tag>
                      </div>
                      <div class="meta-info">
                        <div>{{ formatFileSize(picture.picSize) }}</div>
                        <div>{{ picture.picWidth }}×{{ picture.picHeight }}</div>
                        <div>{{ formatDate(picture.createTime) }}</div>
                      </div>
                      <div v-if="picture.introduction" class="introduction">
                        {{ truncateText(picture.introduction, 30) }}
                      </div>
                      <div v-if="picture.reviewMessage" class="review-message">
                        <a-typography-text
                          type="secondary"
                          :ellipsis="{ tooltip: picture.reviewMessage }"
                          :content="`审核意见：${picture.reviewMessage}`"
                        />
                      </div>
                    </div>
                  </template>
                </a-card-meta>
              </a-card>
            </a-col>
          </a-row>
          <a-empty v-else description="暂无图片数据" />
        </a-spin>
      </div>

      <!-- 分页 -->
      <div class="pagination-wrapper" v-if="pictureList.length > 0">
        <a-pagination
          v-model:current="pagination.current"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :show-size-changer="true"
          :show-quick-jumper="true"
          :show-total="(total: number) => `共 ${total} 条记录`"
          @change="handlePageChange"
        />
      </div>
    </a-card>

    <!-- 图片详情弹窗 -->
    <a-modal
      v-model:open="detailModalVisible"
      title="图片详情"
      width="800px"
      :footer="null"
      centered
    >
      <div v-if="currentPicture" class="picture-detail">
        <a-row :gutter="24">
          <a-col :span="12">
            <div class="picture-preview">
              <a-image
                :src="currentPicture.url"
                :alt="currentPicture.name"
                :preview="true"
                style="width: 100%; max-height: 400px; object-fit: contain"
              />
            </div>
            <div v-if="currentPicture.introduction" class="picture-introduction">
              <h4>图片简介</h4>
              <p>{{ currentPicture.introduction }}</p>
            </div>
            <div v-if="currentPicture.reviewMessage" class="review-message-detail">
              <h4>审核意见</h4>
              <p>{{ currentPicture.reviewMessage }}</p>
            </div>
          </a-col>
          <a-col :span="12">
            <div class="picture-info-section">
              <a-descriptions title="基本信息" :column="1" size="small" bordered>
                <a-descriptions-item label="图片名称">
                  <a-typography-text copyable>{{ currentPicture.name }}</a-typography-text>
                </a-descriptions-item>
                <a-descriptions-item label="审核状态">
                  <a-tag :color="getStatusColor(currentPicture.reviewStatus)">
                    {{ getStatusText(currentPicture.reviewStatus) }}
                  </a-tag>
                </a-descriptions-item>
                <a-descriptions-item label="文件大小">
                  {{ formatFileSize(currentPicture.picSize) }}
                </a-descriptions-item>
                <a-descriptions-item label="图片尺寸">
                  {{ currentPicture.picWidth }}×{{ currentPicture.picHeight }}
                  <a-tag size="small" color="blue" style="margin-left: 8px">
                    {{ formatAspectRatio(currentPicture.picScale) }}
                  </a-tag>
                </a-descriptions-item>
                <a-descriptions-item label="图片格式">
                  <a-tag color="green">{{ currentPicture.picFormat?.toUpperCase() }}</a-tag>
                </a-descriptions-item>
                <a-descriptions-item label="分类">
                  <a-tag v-if="currentPicture.category" color="purple">
                    {{ currentPicture.category }}
                  </a-tag>
                  <span v-else class="text-placeholder">暂无分类</span>
                </a-descriptions-item>
                <a-descriptions-item label="创建时间">
                  {{ formatDate(currentPicture.createTime) }}
                </a-descriptions-item>
                <a-descriptions-item label="审核时间" v-if="currentPicture.reviewTime">
                  {{ formatDate(currentPicture.reviewTime) }}
                </a-descriptions-item>
              </a-descriptions>

              <!-- 标签展示区域 -->
              <div class="tags-section">
                <h4>图片标签</h4>
                <div class="tags-container">
                  <template v-if="getFormattedTags(currentPicture.tags).length > 0">
                    <a-tag
                      v-for="tag in getFormattedTags(currentPicture.tags)"
                      :key="tag"
                      color="blue"
                      class="tag-item"
                    >
                      <template #icon><TagOutlined /></template>
                      {{ tag }}
                    </a-tag>
                  </template>
                  <a-empty v-else :image="false" description="暂无标签" class="empty-tags" />
                </div>
              </div>
              <!-- 操作按钮 -->
              <div class="detail-actions">
                <a-space>
                  <!-- 审核操作按钮 -->
                  <template v-if="currentPicture.reviewStatus === 0">
                    <a-button type="primary" @click="handleReview(currentPicture, 1)">
                      <template #icon><CheckOutlined /></template>
                      通过审核
                    </a-button>
                    <a-button danger @click="handleReview(currentPicture, 2)">
                      <template #icon><CloseOutlined /></template>
                      拒绝审核
                    </a-button>
                  </template>
                </a-space>
              </div>
            </div>
          </a-col>
        </a-row>
      </div>
    </a-modal>

    <!-- 审核弹窗 -->
    <a-modal
      v-model:open="reviewModalVisible"
      :title="reviewForm.reviewStatus === 1 ? '通过审核' : '拒绝审核'"
      @ok="handleConfirmReview"
      @cancel="handleCancelReview"
      :confirm-loading="reviewLoading"
    >
      <a-form :model="reviewForm" layout="vertical">
        <a-form-item
          label="审核意见"
          name="reviewMessage"
          :rules="
            reviewForm.reviewStatus === 2
              ? [{ required: true, message: '拒绝审核必须填写审核意见' }]
              : []
          "
        >
          <a-textarea
            v-model:value="reviewForm.reviewMessage"
            :placeholder="reviewForm.reviewStatus === 1 ? '可选填通过原因' : '请填写拒绝原因'"
            :rows="4"
            :maxlength="500"
            show-count
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 图片编辑弹窗 -->
    <PictureEditModal
      v-model:visible="editModalVisible"
      :picture-data="currentPicture"
      @success="handleEditSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, h } from 'vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import {
  SearchOutlined,
  ReloadOutlined,
  EyeOutlined,
  CheckOutlined,
  CloseOutlined,
  EditOutlined,
  ClockCircleOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  PictureOutlined,
  TagOutlined,
} from '@ant-design/icons-vue'
import { listPictureByPage, reviewPicture, getPictureReviewCount } from '@/api/picture'
import type {
  Picture,
  PictureQueryRequest,
  PictureReviewRequest,
  PictureReviewCountVO,
} from '@/types/picture'
import { PictureEditModal } from '@/components'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const reviewLoading = ref(false)
const pictureList = ref<Picture[]>([])
const detailModalVisible = ref(false)
const reviewModalVisible = ref(false)
const editModalVisible = ref(false)
const currentPicture = ref<Picture | null>(null)

// 搜索表单
const searchForm = reactive<PictureQueryRequest>({
  name: '',
  reviewStatus: undefined,
  category: '',
  current: 1,
  pageSize: 24,
  // 由于是图片审核，确保是从数据库查数据，传输的是用户id。后端以此做判断。
  userId: userStore.loginUser?.id ? String(userStore.loginUser.id) : undefined,
  sortField: 'review_status',
  sortOrder: 'ascend',
})

// 审核表单
const reviewForm = reactive<PictureReviewRequest>({
  id: '0',
  reviewStatus: 0,
  reviewMessage: '',
})

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 24,
  total: 0,
})

// 统计信息
const stats = ref<PictureReviewCountVO>({
  pending: '0',
  approved: '0',
  rejected: '0',
  total: '0',
})

// 获取图片审核统计
const fetchPictureReviewCount = async () => {
  const response = await getPictureReviewCount()
  stats.value = response.data
}

// 获取图片列表
const fetchPictureList = async () => {
  try {
    loading.value = true
    const params = {
      ...searchForm,
      current: pagination.current,
      pageSize: pagination.pageSize,
    }
    const response = await listPictureByPage(params)
    pictureList.value = response.data.records
    pagination.total = response.data.total
  } catch (error) {
    console.error('获取图片列表失败:', error)
    message.error('获取图片列表失败')
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  pagination.current = 1
  fetchPictureList()
}

// 处理重置
const handleReset = () => {
  searchForm.name = ''
  searchForm.reviewStatus = undefined
  searchForm.category = ''
  pagination.current = 1
  fetchPictureList()
}

// 处理分页变化
const handlePageChange = (page: number, pageSize: number) => {
  pagination.current = page
  pagination.pageSize = pageSize
  fetchPictureList()
}

// 查看详情
const handleViewDetail = (picture: Picture) => {
  currentPicture.value = picture
  detailModalVisible.value = true
}

// 处理编辑
const handleEdit = (picture: Picture) => {
  currentPicture.value = picture
  editModalVisible.value = true
}

// 处理编辑成功
const handleEditSuccess = () => {
  editModalVisible.value = false
  fetchPictureList()
  // 如果详情弹窗也打开着，需要刷新详情数据
  if (detailModalVisible.value && currentPicture.value) {
    // 重新获取当前图片数据来更新详情显示
    const updatedPicture = pictureList.value.find((p) => p.id === currentPicture.value?.id)
    if (updatedPicture) {
      currentPicture.value = updatedPicture
    }
  }
}

// 处理审核
const handleReview = (picture: Picture, status: number) => {
  currentPicture.value = picture
  reviewForm.id = picture.id
  reviewForm.reviewStatus = status
  reviewForm.reviewMessage = ''
  reviewModalVisible.value = true
}

// 确认审核
const handleConfirmReview = async () => {
  try {
    reviewLoading.value = true
    await reviewPicture(reviewForm)
    message.success(`${reviewForm.reviewStatus === 1 ? '通过' : '拒绝'}审核成功`)
    reviewModalVisible.value = false
    detailModalVisible.value = false
    fetchPictureList()
  } catch (error) {
    console.error('审核失败:', error)
    message.error('审核失败')
  } finally {
    reviewLoading.value = false
  }
}

// 取消审核
const handleCancelReview = () => {
  reviewModalVisible.value = false
  reviewForm.reviewMessage = ''
}

// 获取图片封面
const getPictureCover = (picture: Picture) => {
  return h('div', { class: 'picture-cover' }, [
    h('img', {
      src: picture.thumbnailUrl || picture.url,
      alt: picture.name,
      style: {
        width: '100%',
        height: '180px',
        objectFit: 'cover',
      },
      onError: (e: Event) => {
        const target = e.target as HTMLImageElement
        target.src =
          ''
      },
    }),
  ])
}

// 获取审核状态样式类
const getReviewStatusClass = (status?: number) => {
  switch (status) {
    case 0:
      return 'pending'
    case 1:
      return 'approved'
    case 2:
      return 'rejected'
    default:
      return ''
  }
}

// 获取状态颜色
const getStatusColor = (status?: number) => {
  switch (status) {
    case 0:
      return 'orange'
    case 1:
      return 'green'
    case 2:
      return 'red'
    default:
      return 'default'
  }
}

// 获取状态文本
const getStatusText = (status?: number) => {
  switch (status) {
    case 0:
      return '待审核'
    case 1:
      return '已通过'
    case 2:
      return '已拒绝'
    default:
      return '未知'
  }
}

// 格式化文件大小
const formatFileSize = (bytes?: number) => {
  if (!bytes) return '-'
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(1024))
  return Math.round((bytes / Math.pow(1024, i)) * 100) / 100 + ' ' + sizes[i]
}

// 格式化日期
const formatDate = (dateString?: string) => {
  if (!dateString) return '-'
  return dayjs(dateString).format('YYYY-MM-DD HH:mm:ss')
}

// 截断文本
const truncateText = (text: string, maxLength: number) => {
  if (!text) return ''
  if (text.length <= maxLength) return text
  return text.substring(0, maxLength) + '...'
}

// 格式化标签（处理可能的JSON字符串或数组）
const getFormattedTags = (tags: string | string[] | undefined): string[] => {
  if (!tags) return []

  if (Array.isArray(tags)) {
    return tags.filter((tag) => tag && tag.trim())
  }

  if (typeof tags === 'string') {
    try {
      // 尝试解析JSON字符串
      const parsed = JSON.parse(tags)
      if (Array.isArray(parsed)) {
        return parsed.filter((tag) => tag && tag.trim())
      }
      return [tags].filter((tag) => tag && tag.trim())
    } catch {
      // 如果不是JSON，按逗号分割
      return tags
        .split(',')
        .map((tag) => tag.trim())
        .filter((tag) => tag)
    }
  }

  return []
}

// 格式化宽高比
const formatAspectRatio = (scale?: number) => {
  if (!scale) return ''
  if (scale > 1) {
    return `${Math.round(scale * 10) / 10}:1`
  } else {
    return `1:${Math.round((1 / scale) * 10) / 10}`
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchPictureList()
  fetchPictureReviewCount()
})
</script>

<style scoped>
.picture-review-container {
  padding: 24px;
}

.search-form {
  margin-bottom: 16px;
  padding: 24px;
  background: #fafafa;
  border-radius: 8px;
}

.stats-cards {
  margin-bottom: 24px;
}

.stat-card {
  text-align: center;
}

.picture-list {
  min-height: 400px;
}

.picture-card {
  height: 100%;
  transition: all 0.3s;
}

.picture-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.picture-card.pending {
  border-left: 4px solid #faad14;
}

.picture-card.approved {
  border-left: 4px solid #52c41a;
}

.picture-card.rejected {
  border-left: 4px solid #ff4d4f;
}

.picture-cover {
  position: relative;
  overflow: hidden;
}

.picture-title {
  display: block;
  font-size: 14px;
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.picture-info {
  font-size: 12px;
}

.status-tag {
  margin-bottom: 8px;
}

.meta-info {
  color: #666;
  margin-bottom: 8px;
}

.meta-info div {
  margin-bottom: 2px;
}

.introduction {
  color: #999;
  font-size: 11px;
  margin-bottom: 8px;
}

.review-message {
  font-size: 11px;
}

.pagination-wrapper {
  margin-top: 24px;
  text-align: center;
}

.picture-detail {
  padding: 16px 0;
}

.picture-preview {
  text-align: center;
  background: #f5f5f5;
  border-radius: 8px;
  padding: 16px;
}

.picture-info-section {
  height: 100%;
}

.tags-section {
  margin-top: 20px;
  padding: 16px;
  background: #fafafa;
  border-radius: 8px;
  border: 1px solid #f0f0f0;
}

.tags-section h4 {
  margin-bottom: 12px;
  font-size: 14px;
  font-weight: 600;
  color: #262626;
}

.tags-container {
  min-height: 40px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: flex-start;
}

.tag-item {
  margin: 0;
  display: inline-flex;
  align-items: center;
  font-size: 12px;
  border-radius: 4px;
  transition: all 0.3s;
}

.tag-item:hover {
  transform: scale(1.05);
}

.empty-tags {
  width: 100%;
  margin: 0;
  padding: 20px 0;
}

.empty-tags :deep(.ant-empty-description) {
  font-size: 12px;
  color: #999;
}

.text-placeholder {
  color: #999;
  font-style: italic;
}

.picture-introduction,
.review-message-detail {
  margin-top: 16px;
}

.picture-introduction h4,
.review-message-detail h4 {
  margin-bottom: 8px;
  font-size: 14px;
  font-weight: 600;
}

.picture-introduction p,
.review-message-detail p {
  margin: 0;
  color: #666;
  line-height: 1.6;
}

.detail-actions {
  margin-top: 24px;
  text-align: center;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

:deep(.ant-card-head-title) {
  font-size: 18px;
  font-weight: 600;
}

:deep(.ant-card-actions > li) {
  margin: 12px 0;
}

:deep(.ant-card-actions > li > span) {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  color: #666;
  font-size: 16px;
  cursor: pointer;
  transition: color 0.3s;
}

:deep(.ant-card-actions > li > span:hover) {
  color: #1890ff;
}

:deep(.ant-descriptions-item-label) {
  font-weight: 600;
}
</style>
